'''

方法汇总

'''

import time,requests,re,os
from pyquery import PyQuery as pq
from config import *
from fontTools.ttLib import TTFont
class Helper( object ):

    def __init__(self):

        pass

    # 获取CSS下载地址
    @staticmethod
    def getCssLink( url = None):

        if not url:

            r = requests.get(url="http://www.dianping.com/shenyang/ch10/r1780", headers=public_for_header)

            if r.status_code == 200:

                doc = pq( r.text )

                css_link = [link.attr("href") for link in (doc("link").items())][6]

                css_link = "http:" + css_link

                data = Helper.getFontLink(  css_link )

                return data


    #获取font下载地址
    @staticmethod
    def getFontLink( url ):

        r = requests.get(url=url, headers=font_for_header)
        # 获取字体下载地址
        font_url = "http:" + re.search(r'shopNum";src:url\(\"(.*?)\"\);', r.text).group(1).replace(".eot", ".woff")
        # 传参到字体下载器
        data = Helper.downloaderTF(font_url)

        return data


    # 解析网页源码下载字体文件到跟目录
    @staticmethod
    def downloaderTF( url ):

        r = requests.get( url = url,headers=font_for_header)

        if r.status_code == 200:

            save_dir = time.strftime('%Y%m%d',time.localtime(time.time()))
            #写入文件
            with open('./'+save_dir+".woff",mode='ab+') as f:

                print("正在写入字体文件:"+save_dir+".woff")

                f.write( r.content )

            print("写入字体文件成功:" + save_dir + ".woff" + "开始进行XML转换")

            # 开始文件转换
            Helper.changeFont( save_dir )

            #开始转换字体
            data = Helper.parseTFXML( save_dir )
            #生成json数据并进行迭代
            return data


    # 字体转换
    @staticmethod
    def changeFont( filename ):

        font = TTFont('./'+filename+'.woff')

        font.saveXML('./'+filename+'.xml')

        # 删除woff文件
        os.remove( filename+'.woff' )

        print("文件转换成功开始进行字体JSON转换")


    #解析字体文件为json格式
    @staticmethod
    def parseTFXML( filename ):

        import xmltodict

        xml = open('./'+filename+'.xml', mode='r').read()

        xp = xmltodict.parse(xml)

        fontDict = []

        for order in (xp["ttFont"]["GlyphOrder"]["GlyphID"]):

            data = {

                "name": order["@name"].replace("uni", ""),

                "id": order["@id"]

            }

            fontDict.append( data )

        return fontDict



if __name__ == '__main__':

    Helper.changeFont("9213d34e")
    Helper.parseTFXML("9213d34e")


